<template>
  <!--表单组件:并非行内-->
  <el-form label-width="80px">
    <el-form-item label="SPU名称"> {{spuName}}</el-form-item>
    <el-form-item label="SKU名称">
      <el-input placeholder="请你输入SKU名称" v-model="skuParams.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)">
      <el-input type="number" placeholder="价格(元)" v-model="skuParams.price"></el-input>
    </el-form-item>
    <el-form-item label="重量(千克)">
      <el-input type="number" placeholder="重量(千克)" v-model="skuParams.weight"></el-input>
    </el-form-item>
    <el-form-item label="规格描述">
      <el-input type="textarea" placeholder="规格描述" v-model="skuParams.skuDesc"></el-input>
    </el-form-item>
    <!--平台属性-->
    <el-form-item label="平台属性">
      <!--行内form:因为一行放置多个select-->
      <el-form :inline="true">
        <el-form-item :label="attr.attrName" v-for="(attr, index) in attrArr" :key="attr.id">
          <el-select v-model="attr.attrIdAndValueId">
            <el-option :label="item.valueName" :value="`${attr.id}:${item.id}`"
              v-for="(item, index) in attr.attrValueList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <!--行内form:因为一行放置多个select-->
      <el-form :inline="true">
        <el-form-item :label="saleAttr.saleAttrName" v-for="(saleAttr, index) in saleArr" :key="saleAttr.id">
          <el-select v-model="saleAttr.saleAttrIdAndValueId">
            <el-option :label="item.saleAttrValueName" :value="`${saleAttr.id}:${item.id}`"
              v-for="(item, index) in saleAttr.spuSaleAttrValueList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="图片名称">
      <el-table border :data="imgArr" ref="tableRef">
        <el-table-column width="80" type="selection"></el-table-column>
        <el-table-column label="图片">
          <template #="{ row, $index }">
            <img :src="row.imgUrl" alt="图片没了" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" v-if="row.isChecked == 1">默认</el-button>
            <el-button type="info" size="small" v-else @click="changeChecked(row)">设置默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>
  
<script setup lang="ts">
//平台属性|销售属性|照片墙数据
import {
  reqAttrList,
  reqSpuHasSaleAttr,
  reqImgList,
  reqAddSku,
} from "../../../api/product/spu/spu";
import { ElMessage } from "element-plus";
import { ref } from "vue";
let spuName = ref()
//存储平台属性
let attrArr = ref([]);
//存储销售属性
let saleArr = ref([]);
//存储照片墙的数据
let imgArr = ref([]);
//获取table组件
let tableRef = ref();
//收集添加SKU参数
let skuParams = ref({
  //父组件传递过来参数
  category3Id: 0, //三级分类的ID
  spuId: 0, //SPU的ID
  tmId: 0, //spu的品牌的ID

  //v-model收集
  skuName: "", //sku的名字
  price: 0, //sku的价格
  weight: "", //sku的重量
  skuDesc: "", //sku的描述

  skuDefaultImg: "", //默认图片地址
  skuAttrValueList: [
    //平台属性
    // {
    //   attrId: 0, //属性的id
    //   valueId: 0, //属性值的ID
    // },
  ],
  skuSaleAttrValueList: [
    //销售属性
    // {
    //   saleAttrId: 0,
    //   saleAttrValueId: 0,
    // },
  ],
});
//子组件的方法:当父组件点击添加SKU按钮时候调用
const initSku = async (
  c1Id: string | number,
  c2Id: string | number,
  spu: any
) => {
  console.log(spu)
  spuName.value = spu.spuName
  //收集三级分类的ID|SPUID|TMID
  skuParams.value.category3Id = spu.category3Id;
  skuParams.value.spuId = spu.id;
  skuParams.value.tmId = spu.tmId;
  //全部平台属性
  let result = await reqAttrList(c1Id, c2Id, spu.category3Id);
  //销售属性
  let result1 = await reqSpuHasSaleAttr(spu.id);
  //照片墙
  let result2 = await reqImgList(spu.id);
  //存储数据:平台属性
  attrArr.value = result;
  //存储数据:销售属性
  saleArr.value = result1;
  //照片墙
  imgArr.value = result2;
  if (imgArr.value.length == 0) return;
  //由于服务器返回的数据没有控制默认按钮标记：只能自己手动添加
  //添加一个字段:isChecked 1 默认  0不是默认
  imgArr.value[0].isChecked = 1;
  setTimeout(() => {
    tableRef.value.toggleRowSelection(imgArr.value[0], true);
    skuParams.value.skuDefaultImg = imgArr.value[0].imgUrl;
  }, 0);
  //添加isChecked = 0；
  for (var i = 0; i < imgArr.value.length - 1; i++) {
    if (i > 0) {
      imgArr.value[i].isChecked = 0;
    }
  }
};

//切换checked
const changeChecked = (row) => {
  //全部图片先变成0
  imgArr.value.forEach((item) => {
    item.isChecked = 0;
    //全部table复选框不勾选
    tableRef.value.toggleRowSelection(item, false);
  });
  //选中图片设置为默认
  row.isChecked = 1;
  //table组件实例:toggleRowSelection 设置某一行能否被选中
  tableRef.value.toggleRowSelection(row, true);
  //收集服务器需要携带的参数
  skuParams.value.skuDefaultImg = row.imgUrl;
};

//保存按钮
const save = async () => {
  //整理参数
  //整理平台属性
  skuParams.value.skuAttrValueList = attrArr.value.reduce((prev, next) => {
    //next:当前平台属性数组里面每一个元素
    //判断：当前品台属性对象是否有attrIdAndValueId属性，如果有说明用户在这个属性里面勾选了
    if (next.attrIdAndValueId) {
      //把字符串切割为数组
      const [attrId, valueId] = next.attrIdAndValueId.split(":");
      //整理成对象添加数组里面:对象，分别存储属性ID与属性值的ID
      prev.push({ attrId, valueId });
    }
    return prev;
  }, []);

  //发请求+添加SKU
  try {
    await reqAddSku(skuParams.value);
    //请求成功:通知父组件切换场景0 + 提示信息
    //提示框
    ElMessage({
      type: "success",
      message: "添加SKU成功",
    });
    emit("changeScene", { sences: 0, flag: "" });
    //情况数据
    resetData();
  } catch (error) {
    ElMessage({
      type: "error",
      message: "添加SKU失败" + error,
    });
  }
}
//重置数据方法
const resetData = () => {
  attrArr.value = [];
  saleArr.value = [];
  imgArr.value = [];
  skuParams.value = {};
}

//取消的方法
const cancel = () => {
  console.log(123);
  //触发自定义事件
  emit('changeScene', {
    sences: 0,
    flag: "",
  })
  resetData();
}
//请求失败:提示信息
defineExpose({
  initSku,
});
let emit = defineEmits(["changeScene"]);
</script>
  
<style scoped>

</style>